//
//  CLChatVolumeView.swift
//  ChatDemo
//
//  Created by 范强伟 on 2024/5/16.
//

import UIKit

class CLChatVolumeView: UIView {

    let k_volumeViewHeight  =   40.0
    let k_volumeCount       =   20.0
    let k_volumeLineWidth   =   3.0
    let k_volumeLineDistance =  3.0
    
    var soundMeters = Array<Double>()
    
    var color: UIColor = .white
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        self.contentMode = .redraw
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NSNotification.Name("updateMeters"), object: nil)
        
    }

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     
    override func draw(_ rect: CGRect) {
        if soundMeters.count > 0 {
            let context = UIGraphicsGetCurrentContext()
            context?.setLineCap(.round)
            context?.setLineJoin(.round)
            context?.setStrokeColor(color.cgColor)
            
             
            let maxVolume = k_volumeViewHeight
            context?.setLineWidth(k_volumeLineWidth)
            
            soundMeters.enumerated().forEach { (idx, obj) in
                let item = obj 
                let barHeight = maxVolume * item
                var start_y: CGFloat = .leastNormalMagnitude
                if barHeight > maxVolume {
                    start_y = 0.0
                } else {
                    start_y = (maxVolume - barHeight) / 2
                }
                NSLog("%f  %f", start_y,barHeight)
                context?.move(to: CGPoint(x: CGFloat(idx) * 6.0 + 3.0, y: start_y))
                context?.addLine(to: CGPoint(x: CGFloat(idx) * 6.0 + 3.0, y: start_y + barHeight))
            }
            context?.strokePath()
             
        }
         
        
    }
    
    @objc func reloadData(_ notification: NSNotification){
        guard let soundMeters = notification.object as? [Double] else { return  }
        self.soundMeters = soundMeters
        DispatchQueue.main.async {[weak self] in
            guard let weakself = self else { return }
            weakself.setNeedsDisplay()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
